<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="小程序名称">
                <a-input placeholder="请输入小程序名称" v-model="queryParam.mini_nickname" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="申请状态">
                <a-select v-model="queryParam.status">
                  <a-select-option :value="0"> 全部 </a-select-option>
                  <a-select-option :value="1"> 完善资料 </a-select-option>
                  <a-select-option :value="2"> 成功 </a-select-option>
                  <a-select-option :value="3"> 失败 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.is_use" @change="getList">
          <a-radio-button :value="0"> 全部 </a-radio-button>
          <a-radio-button :value="1"> 已使用 </a-radio-button>
          <a-radio-button :value="2"> 未使用 </a-radio-button>
        </a-radio-group>
        <div>
          <a-button type="primary" v-if="!hasChannel" @click="$router.push('/setting/appletManagement/chooseType')"
            >+ 新增</a-button
          >
          <a-button type="primary" v-else @click="$router.push('/saasChannel/applet/chooseType')">+ 新增</a-button>
          <!-- <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="allChangeStatus('open')">批量启用</a-menu-item>
              <a-menu-item @click="allChangeStatus('disabled')">批量禁用</a-menu-item>
              <a-menu-item @click="allChangeStatus('delete')">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown> -->
        </div>
      </div>
      <!-- <a-alert type="info" show-icon style="margin-bottom: 10px">
        <span slot="message">
          已选择 <span style="color: red">{{ selectedRowKeys.length }}</span> 项
        </span>
      </a-alert> -->
      <a-table
        :rowKey="
          (r, i) => {
            return i
          }
        "
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :columns="columns"
        :data-source="list"
      >
        <div slot="user" slot-scope="scope">
          <div class="name">
            <div class="pic">
              <img :src="scope.mini_url" alt="" v-if="scope.mini_url" />
              <img src="../../assets/images/defaultMini.png" alt="" v-else />
            </div>
            <div class="info">
              <template v-if="scope.is_finish == 1">
                <span>{{ scope.nickname }}</span>
                <span>{{ scope.categories.map((item) => item.first_name + ' => ' + item.second_name).join() }}</span>
              </template>
              <template v-else>
                <span v-if="scope.status == -1">注册中</span>
                <span v-if="scope.status == 0 || scope.status == 1">恭喜您成功注册小程序</span>
                <span v-if="scope.status == 2">小程序审核失败！</span>
                <span v-if="scope.status == -1">小程序注册中</span>
                <span v-if="scope.status == 0 || scope.status == 1">
                  {{ scope.is_finish == 0 ? '填写小程序基本信息，即可进行审核发布' : '请点击审核，审核发布小程序' }}
                </span>
                <span v-if="scope.status == 2">修改信息后，在重新提交</span>
              </template>
            </div>
          </div>
        </div>
        <div slot="appid" slot-scope="scope">
          {{ scope.appid ? scope.appid : '-' }}
        </div>
        <div slot="status" slot-scope="scope">
          <a-tooltip placement="top">
            <template slot="title" v-if="scope.status == 2 || (scope.status == 1 && scope.is_finish == 0)">
              <span v-html="scope.msg"></span>
              <div v-html="scope.mini_up_error"></div>
            </template>
            <a-tag color="orange" v-if="scope.status == -1"> 注册中 </a-tag>
            <template v-if="scope.status == 0 || scope.status == 1">
              <a-tag color="orange" v-if="scope.is_finish == 0"> 完善资料 </a-tag>
              <a-tag color="blue" v-if="scope.is_finish == 1"> 认证成功 </a-tag>
            </template>
            <a-tag color="red" v-if="scope.status == 2"> 认证失败 </a-tag>
          </a-tooltip>
        </div>
        <span slot="use" slot-scope="scope">
          <span v-if="scope.is_use == 1">已使用</span>
          <span v-if="scope.is_use == 2">未使用</span>
        </span>
        <span slot="created_at" slot-scope="text">
          {{ text > 0 ? $moment(text * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>
        <div slot="issue" slot-scope="scope">
          <div class="status">
            <span
              :class="
                scope.mini_up <= 0
                  ? 'gray'
                  : scope.mini_up == 1
                  ? 'orange'
                  : scope.mini_up == 2
                  ? 'green'
                  : scope.mini_up == 3
                  ? 'red'
                  : scope.mini_up == 4
                  ? 'orange'
                  : scope.mini_up == 5
                  ? 'green'
                  : ''
              "
            ></span>
            <a-tooltip placement="top">
              <template slot="title" v-if="scope.mini_up == 3">
                <span v-html="scope.mini_up_error"></span>
              </template>
              <div>
                {{
                  scope.mini_up == -1
                    ? '创建中'
                    : scope.mini_up == 0
                    ? '创建中'
                    : scope.mini_up == 1
                    ? '审核中'
                    : scope.mini_up == 2
                    ? '审核通过'
                    : scope.mini_up == 3
                    ? '审核失败'
                    : scope.mini_up == 4
                    ? '延迟审核'
                    : scope.mini_up == 5
                    ? '已发布'
                    : ''
                }}
              </div>
            </a-tooltip>
          </div>
        </div>
        <div slot="action" slot-scope="scope" class="action">
          <a-button type="link" @click="wright(scope)" :disabled="scope.status == -1" v-if="scope.is_finish == 0"
            >填写</a-button
          >
          <a-button
            type="link"
            @click="upload(scope)"
            v-if="scope.is_finish == 1 && (scope.status == 0 || scope.status == 1) && scope.mini_up == 0"
            >上传</a-button
          >
          <a-button
            type="link"
            @click="previewApplet(scope)"
            v-if="scope.is_finish == 1 && (scope.status == 0 || scope.status == 1) && scope.mini_up != 0"
            >预览</a-button
          >
          <a-button type="link" @click="cancleCheck(scope.id)" v-if="scope.mini_up == 1 || scope.mini_up == 4"
            >取消审核</a-button
          >
          <a-button
            type="link"
            @click="issue(scope)"
            :disabled="scope.mini_up == 5"
            v-if="scope.is_finish == 1 && (scope.mini_up == 2 || scope.mini_up == 5)"
            >发布</a-button
          >
          <a-divider type="vertical" />
          <a-dropdown>
            <a-button type="link" :disabled="parseInt(scope.status) !== 0 && parseInt(scope.status) !== 1">
              更多 <a-icon type="down" />
            </a-button>
            <a-menu slot="overlay" v-if="parseInt(scope.status) === 0 || parseInt(scope.status) === 1">
              <a-menu-item v-if="scope.is_use == 2 && scope.mini_up == 5" @click="useApplet(1, scope.id)">
                <a href="javascript:;">使用小程序</a>
              </a-menu-item>
              <!-- <a-menu-item v-if="scope.is_use == 1 && scope.mini_up == 5" @click="useApplet(2, scope.id)">
                <a href="javascript:;">暂停使用小程序</a>
              </a-menu-item> -->
              <!-- <a-menu-item v-if="scope.is_use == 1">
                <a href="javascript:;">版本信息</a>
              </a-menu-item> -->
              <a-menu-item>
                <a href="javascript:;" @click="wright(scope)">编辑小程序</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm
                  title="解除后将失去目前所有关联的普通二维码。"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="delQrcode(scope)"
                >
                  <a href="javascript:;">解除关联二维码</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-if="scope.mini_up == 5">
                <a
                  href="javascript:;"
                  @click="
                    showQrcode = true
                    qrcodeUrl = scope.qr
                  "
                  >小程序二维码</a
                >
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
      </a-table>
    </a-card>
    <!-- 上传代码弹窗 -->
    <a-modal v-model="showUpload" title="上传代码" @ok="uploadApplet" :confirmLoading="btnLoading">
      <a-form-model
        ref="checkForm"
        :model="checkForm"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        :destroyOnClose="true"
      >
        <a-form-model-item label="小程序版本号">
          <a-input v-model="checkForm.user_version" disabled></a-input>
        </a-form-model-item>
        <a-form-model-item label="是否开启直播" prop="is_live">
          <a-switch
            :checked="checkForm.is_live ? true : false"
            @change="(e) => (e ? (checkForm.is_live = 1) : (checkForm.is_live = 0))"
          />
        </a-form-model-item>
        <a-form-model-item label="小程序代码描述" prop="user_desc">
          <a-textarea v-model="checkForm.user_desc" placeholder="小程序描述" :rows="4" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 提交审核弹窗 -->
    <a-modal v-model="showCheck" title="提交审核" @ok="checkApplet" :afterClose="closeModal">
      <a-form-model-item label="是否加急" prop="is_fast_audit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-radio-group v-model="is_fast_audit">
          <a-radio :value="0"> 不加急 </a-radio>
          <a-radio :value="1"> 加急(一年3次)</a-radio>
        </a-radio-group>
        <div style="font-size: 14px; color: rgba(0, 0, 0, 0.45); line-height: normal">
          选择不加急审核，预计在1-7天内完成审核。
        </div>
        <div style="font-size: 14px; color: rgba(0, 0, 0, 0.45); line-height: normal">
          若代码中包含复杂逻辑或其他特殊情况，可能会导致审核时间延长。
        </div>
      </a-form-model-item>
    </a-modal>
    <a-modal v-model="showPreview" title="预览小程序" :width="700" okText="提交审核" :afterClose="closeModal">
      <div class="qrBox">
        <div class="qrCode">
          <img :src="qrCode" alt="" v-if="qrCode && qrCode != ''" />
          <span v-else>请点击更新模板生成预览二维码</span>
        </div>
        <div class="add">
          <p>添加小程序体验者：</p>
          <a-input-search
            v-model="wechatId"
            enter-button="添加"
            placeholder="请输入微信号添加"
            @search="addPreviewer"
            style="margin: 24px 0"
          />
          <a-button type="link" v-if="currentApplet.qr" @click="downloadIamge(currentApplet.qr, '小程序码')"
            >下载正式版小程序码</a-button
          >
        </div>
      </div>
      <div slot="footer">
        <a-button @click="showPreview = false">取消</a-button>

        <a-button @click="cancleCheck(mini_id)" v-if="mini_up == 1 || mini_up == 4">取消审核</a-button>
        <template v-else>
          <a-button type="primary" @click="upload(currentApplet)">更新模板</a-button>
          <a-button type="primary" @click="toCheck">提交审核</a-button>
        </template>
      </div>
    </a-modal>
    <a-modal v-model="showQrcode" title="小程序二维码" @ok="showQrcode = false">
      <div class="qrBox">
        <div class="qrCode">
          <img :src="qrcodeUrl" alt="" />
        </div>
      </div>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import {
  list,
  check,
  preview,
  addPreviewer,
  useApplet,
  cancleCheck,
  authorization,
  issue,
  upload,
  officialQr,
  canUsePlugin,
  delBindQrcode,
} from '@/api/setting/applet'
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '基本信息',
    scopedSlots: {
      customRender: 'user',
    },
    width: 380,
  },
  {
    title: '申请状态',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: 'AppId',
    scopedSlots: {
      customRender: 'appid',
    },
  },
  {
    title: '是否使用小程序',
    scopedSlots: {
      customRender: 'use',
    },
  },
  {
    title: '发布状态',
    scopedSlots: {
      customRender: 'issue',
    },
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
    width: 220,
  },
]
export default {
  data() {
    return {
      // 验证规则
      rules: {
        user_desc: [{ required: true, message: '请输入小程序代码简介', trigger: 'blur' }],
      },
      queryParam: {
        // 小程序名称
        mini_nickname: '',
        // 申请状态
        status: 0,
        // 使用状态
        is_use: 0,
        pageNo: 1,
        pageSize: 10,
      },
      // 小程序列表
      list: [],
      // 总数
      totalCount: 0,
      columns,
      // 是否显示提交审核的弹窗
      showCheck: false,
      // 提交审核的表单
      checkForm: {
        user_version: '',
        user_desc: '',
        is_live: 0,
      },
      // 展示预览小程序的弹窗
      showPreview: false,
      // 小程序二维码地址
      qrCode: '',
      // 添加体验者的微信号
      wechatId: '',
      // 当前正在修改的小程序
      currentApplet: {},
      // 显示提交代码弹窗
      showUpload: false,
      // 是否加急
      is_fast_audit: 0,
      // 是否显示正式版二维码的弹窗
      showQrcode: false,
      // 显示的二维码地址
      qrcodeUrl: '',
      // 俺就是否正在加载中
      btnLoading: false,
      //点击的小程序状态
      mini_up: 0,
      //点击的小程序id
      mini_id: 0,

      hasChannel: false,
    }
  },
  methods: {
    // 关闭弹窗
    closeModal() {
      this.checkForm.user_version = ''
      this.checkForm.user_desc = ''
      this.checkForm.is_live = 0
      this.wechatId = ''
      this.qrCode = ''
    },
    // 获取小程序列表
    async getList() {
      const hide = this.$message.loading('加载中', 0)
      const res = await list(this.queryParam)
      console.log(res)
      if (res.code == 0) {
        this.totalCount = res.totalCount
        this.list = res.data
      }
      hide()
    },
    // 分页请求
    tablePageChange(e) {
      this.queryParam.pageNo = e
      this.getList()
    },
    // 点击完善资料
    wright(e) {
      if (this.hasChannel) {
        if (e.status == 2) {
          this.$router.push('/saasChannel/applet/writeInformation?id=' + e.id)
        } else {
          this.$router.push('/saasChannel/applet/completeInformation?id=' + e.id)
        }
        return
      }

      if (e.status == 2) {
        return this.$router.push('/setting/appletManagement/writeInformation?id=' + e.id)
      }
      this.$router.push('/setting/appletManagement/completeInformation?id=' + e.id)
    },
    async delQrcode(e) {
      const hide = this.$message.loading('加载中', 0)
      const res = await delBindQrcode({ id: e.id })
      hide()
      if (res.code == 0) {
        this.showCheck = false
        this.getList()
      }
    },
    // 提交审核小程序
    async checkApplet() {
      const hide = this.$message.loading('加载中', 0)
      const res = await check({ ...this.checkForm, id: this.currentApplet.id })
      hide()
      if (res.code == 0) {
        this.showCheck = false
        this.getList()
      }
    },
    // 点击审核小程序
    async toCheck() {
      this.showPreview = false
      this.showCheck = true
    },
    // 点击预览小程序
    async previewApplet(e) {
      console.log(e)
      this.currentApplet = e
      this.qrCode = e.qrcode
      this.showPreview = true
      this.mini_up = e.mini_up
      this.mini_id = e.id
      // const res = await preview({ id: e.id })
      // if (res.code == 0) {
      //   this.currentApplet = e
      //   this.qrCode = res.data
      //   this.showPreview = true
      // }
    },
    // 点击确定添加小程序体验者
    async addPreviewer() {
      if (this.wechatId && this.wechatId != '') {
        const hide = this.$message.loading('加载中', 0)
        const res = await addPreviewer({ wechatId: this.wechatId, id: this.currentApplet.id })
        hide()
        console.log(res)
        if (res.code == 0) {
          this.$message.success('添加成功')
          this.wechatId = ''
        }
      }
    },
    // 点击下载小程序码
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png') //得到图片的base64编码数据

        var a = document.createElement('a') // 生成一个a元素
        var event = new MouseEvent('click') // 创建一个单击事件
        a.download = name || 'photo' // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = imgsrc
    },
    // 点击使用或者暂时使用小程序
    useApplet(e, id) {
      let that = this
      let text = e == 0 ? '确认暂停使用小程序' : '确认使用小程序'
      this.$confirm({
        title: text,
        onOk() {
          useApplet({ is_use: e, id }).then((res) => {
            if (res.code == 0) {
              that.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 点击取消审核
    cancleCheck(id) {
      this.$confirm({
        title: '确认撤回审核？',
        onOk: () => {
          const hide = this.$message.loading('加载中', 0)
          cancleCheck({ id }).then((res) => {
            hide()
            if (res.code == 0) {
              this.showPreview = false
              this.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 通过code解析授权信息
    async authorization(auth_code) {
      try {
        const res = await authorization({ auth_code })
        location.replace(location.href.replace(location.hash, `#${this.$route.path}`))
        this.getList()
      } catch (error) {
        this.getList()
        location.replace(location.href.replace(location.hash, `#${this.$route.path}`))
      }
    },
    // 点击发布小程序
    issue(scope) {
      this.$confirm({
        title: '确认发布小程序',
        onOk: () => {
          const hide = this.$message.loading('加载中', 0)
          issue({ id: scope.id }).then((res) => {
            hide()
            if (res.code == 0) {
              this.getList()
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 点击上传代码
    upload(e) {
      this.currentApplet = e
      this.checkForm.user_version = e.user_version
      this.checkForm.is_live = e.is_live
      this.showUpload = true
    },
    // 点击上传代码
    async uploadApplet() {
      if (this.checkForm.is_live) {
        const authRes = await canUsePlugin({
          id: this.mini_id,
        })
        if (authRes.code) {
          this.$message.error(authRes.msg)
          return
        }
      }

      this.$refs['checkForm'].validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          const res = await upload({ ...this.checkForm, id: this.currentApplet.id })
          if (res.code == 0) {
            this.showUpload = false
            this.qrCode = res.data
            this.btnLoading = false
            this.getList()
          } else {
            this.btnLoading = false
          }
        } else {
          return false
        }
      })
    },
  },
  mounted() {
    if (this.$route.query.auth_code) {
      this.authorization(this.$route.query.auth_code)
    } else {
      this.getList()
    }

    if (this.$route.meta.hasChannel) {
      this.hasChannel = true
    }
  },
}
</script>

<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.status {
  display: flex;
  align-items: center;
  span:nth-child(1) {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
  }
  .gray {
    background-color: #c6c6c6;
  }
  .green {
    background-color: #65c817;
  }
  .red {
    background-color: #ff4d4f;
  }
  .orange {
    background-color: #faad14;
  }
}
.action {
  /deep/ .ant-divider {
    margin: 0;
  }
}
.qrBox {
  display: flex;
  .qrCode {
    width: 300px;
    height: 300px;
    padding: 20px;
    background-color: #fafafa;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
